<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import { useWebSocket,useDateText } from '@/hooks'
const ws = useWebSocket(handleMessage);
const router = useRouter();
// 定义消息
const msg = ref('');
// 消息数组
const msgList = reactive([]);
const msgClick = () => {
  // 判断有无输入
  if (!msg.value.trim()) {
    return
  }
  // 输入了, 发送消息
  ws.send(JSON.stringify(
    {
      id: useDateText(new Date().getTime()),
      username: localStorage.getItem('username'),
      message: msg.value,
      date: useDateText(new Date().getTime())
    }
  ));

  // 添加完毕, 需要清空输入框
  msg.value = '';
}
// 在mounted中判断是否有username
onMounted(() => {
  const _username = localStorage.getItem('username');
  if (!_username) {
    router.push('/')
  }
})

function handleMessage(e) {
  console.log(e);
  const data = e.data;
  if (data instanceof Blob) {
    const reader = new FileReader();
    // 读取数据
    reader.readAsText(data);
    reader.onload = () => {
      msgList.push(JSON.parse(reader.result));
    }
  } else {
    console.log('接收到的数据类型不是 Blob');
  }
}
</script>

<template>
  <!-- 消息展示区域 -->
  <ul>
    <li v-for="item in msgList" :key="item.id">
      <p>
        <span class="user">{{ item.username }} {{ item.date }}</span>
      </p>
      <p>
        <span class="msg">{{ item.message }}</span>
      </p>
    </li>
  </ul>
  <div>
    <input type="text" placeholder="请输入消息" v-model="msg">
    <button @click="msgClick">发送消息</button>
  </div>
</template>

<style>
.user {
  color: pink;
}
.msg {
  color: skyblue;
}
</style>